package com.taotao.netty.handler;

import com.alibaba.fastjson2.JSON;
import com.taotao.netty.Command;
import com.taotao.netty.constant.CommandType;
import com.taotao.netty.domain.Result;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/**
 * @className: WebSocketHandler
 * @author: ZhangYuQi
 * @date: 2025/2/26 下午3:38
 * @Version: 1.0
 * @description:
 */


public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) throws Exception {
        System.out.println("收到消息：" + frame.text());

        try {
            //解析消息 传输以JSON
            Command command= JSON.parseObject(frame.text(), Command.class);

            switch (CommandType.match(command.getCode())){
                case CONNECTION -> ConnectionHandler.execute(ctx, command);

                case CHAT -> ChatHandler.execute(ctx, frame);

                case JOIN_GROUP -> JoinGroupHandler.execute(ctx);

                case OFFLINE -> OfflineHandler.execute(ctx,command);

                default ->  ctx.channel().writeAndFlush(Result.fail("不支持的Code"));
            }
        } catch (Exception e) {
            ctx.channel().writeAndFlush(Result.fail(e.getMessage()));
        }

    }
}
